package com.gin.kotlin.gf2gamecommunity.pagingsource

import android.util.Log
import com.gin.kotlin.gf2gamecommunity.base.livedata.AbstractPagingSource
import com.gin.kotlin.response.ListData
import com.gin.kotlin.response.Res
import retrofit2.Call
import retrofit2.await

abstract class AbstractListDataPagingSource<T : Any, D : ListData<T>> : AbstractPagingSource<T>() {
    private val cachedData = hashMapOf<Int, D>()

    abstract fun request(page: Int, size: Int): Call<Res<D>>

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, T> {
        val tag = this::class.java.simpleName
        val page = params.key ?: 1
        val size = params.loadSize
        val cache = cachedData[page]
        if (cache != null) {
            Log.i(tag, "缓存命中: page = $page")
            return handleData(page, size, cache)
        }
        Log.i(tag, "查询 page:$page, size:$size")
        try {
            val data = request(page, size).await().data ?: return LoadResult.Page(listOf(), null, null)
            cachedData[page] = data
            return handleData(page, size, data)
        } catch (e: Exception) {
            e.printStackTrace()
            return LoadResult.Error(e)
        }
    }

    private fun handleData(page: Int, size: Int, data: D) =
        LoadResult.Page(data.list, null, if (page * size < data.total) page + 1 else null)


    companion object {
        private val TAG = AbstractListDataPagingSource::class.java.simpleName
    }
}